require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` });
// set up for Debug mode
// require("dotenv").config({ path: `.env.development` });
// process.env.NODE_ENV="development";
const bodyParser = require("body-parser");
const cookieParser=require("cookie-parser");
const express = require("express");
const cors = require("cors");
const https = require("https");
const http = require("http");
const fs = require("fs");
const app = express();
app.use(cors());
app.use(express.json()); // to parse JSON bodies
app.use(cookieParser());

//设置跨域访问
app.all("*",function(req,res,next){
  // console.log(req);

  let originHeader = req.header("Origin");
  if(!originHeader || originHeader === ''){
      originHeader = "*";
  }
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", originHeader);
  res.header("Access-Control-Allow-Credentials","true");
  //允许的header类型
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  res.header("Access-Control-Expose-Headers", "Authorization,Access-Control-Allow-Origin");
  if (req.method.toLowerCase() == 'options')
      res.send(200);  //让options尝试请求快速结束
  else
      next();
})


if(process.env.AUTH != 'token'){
  const session=require("express-session");
  const MongoStore = require("connect-mongo");
  app.use(
    session({
      name: 'session-id',
      secret: "wind", // 服务器生成 session 的签名
      resave: true,     //每次是否都刷新到期时间
      saveUninitialized: true, //强制将为初始化的 session 存储(该session_id是没有用的)
      cookie: {
        maxAge: 1000 * 60 * 60,// 过期时间
        secure: false, // 为 true 时候表示只有 https 协议才能访问cookie
      },
      //自动在mongodb中创建一个数据库存储session，并且过期时间也会同步刷新
      store: MongoStore.create({
        mongoUrl: process.env.DB_URL,
        ttl: 1000 * 60 * 60 // 过期时间
      }),
    })
  );
}

//定义错误级别的中间件，捕获整个项目的异常错误，从而防止程序的崩溃
app.use((err, req, res, next) => {
  console.log('server error: ' + err.message);
  res.send({ code: 500, msg: "server error." })
})

// static resource
app.use(express.static('uploads'))

require("./db"); // require the db.js

// Require your routes
const BASE_API = "/api";
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const fileRoutes = require('./routes/fileRoutes');
const menuRoutes = require('./routes/menuRoutes');
const roleRoutes = require('./routes/roleRoutes');
const dictTypeRoutes = require('./routes/dictTypeRoutes');
const dictDataRoutes = require('./routes/dictDataRoutes');
const roleMenuRoutes = require('./routes/roleMenuRoutes');
const userRoleRoutes = require('./routes/userRoleRoutes');
{% for table in schema['tables'] %}
const {{table['alias']}}Routes = require('./routes/{{table['alias']}}Routes');
{%- endfor %}

// Use your routes
app.use(BASE_API + '/auth', authRoutes);
app.use(BASE_API + '/file', fileRoutes);
app.use(BASE_API + '/sysUser', userRoutes);
app.use(BASE_API + '/sysMenu', menuRoutes);
app.use(BASE_API + '/sysRole', roleRoutes);
app.use(BASE_API + '/sysDictType', dictTypeRoutes);
app.use(BASE_API + '/sysDictData', dictDataRoutes);
app.use(BASE_API + '/sysRoleMenu', roleMenuRoutes);
app.use(BASE_API + '/sysUserRole', userRoleRoutes);
{% for table in schema['tables'] %}
app.use(BASE_API + '/{{table['alias']}}', {{table['alias']}}Routes);
{%- endfor %}
// ... other imports and app setup ...

let server;
let privateKey;
let certificate;

if (process.env.NODE_ENV === "development") {
  server = http.createServer(app);
} else {

  const privateKeyPath = "/etc/letsencrypt//privkey.pem";
  const certificatePath = "/etc/letsencrypt/certificate.pem";

  if (fs.existsSync(privateKeyPath) && fs.existsSync(certificatePath)) {
    privateKey = fs.readFileSync(privateKeyPath, "utf8");
    certificate = fs.readFileSync(certificatePath, "utf8");

    const credentials = {
      key: privateKey,
      cert: certificate,
    };
    server = https.createServer(credentials, app);
  } else {
    console.warn("SSL certificates not found. Falling back to HTTP.");
    console.log("DB_URL:", process.env.DB_URL);
    server = http.createServer(app);
  }
}

const port = process.env.PORT || 8181;
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
